//
//  LZMyMessageCenterViewController.m
//  laziz_Merchant
//
//  Created by xbnzd on 17/3/1.
//  Copyright © 2017年 XBN. All rights reserved.
//

#import "LZMyMessageCenterViewController.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "LZRestaurantAuthenticationViewController.h"
#import "LZMsgCenterCommentViewController.h"
#import "LZFinancialDetailViewController.h"
#import "LZManagePictureContentViewController.h"
#import "GVUserDefaults+LZProperties.h"
#import "LZMyMessageCenterCell.h"
#import "UITableView+LZTableView.h"
#import "MJRefresh.h"
#import "extobjc.h"

#import "LZNotificationPresenter.h"
#import "LZMsgCenterPresenter.h"
#import "LZMessageModel.h"
#import "LZAlertView.h"

@interface LZMyMessageCenterViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) LZMsgCenterPresenter *msgPresenter;
@property (assign, nonatomic) NSTimeInterval timeStamp;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, strong) NSMutableArray *dataArr;

@end

@implementation LZMyMessageCenterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _dataArr = @[].mutableCopy;
    _msgPresenter = [[LZMsgCenterPresenter alloc] init];
    _timeStamp = 0;
    _currentPage = 1;
    
    [self configureUI];
    
    [self addHeaderRefresh];
    [self addFooterRefresh];
    
    [self.tableView.mj_header  beginRefreshing];
    
}

#pragma mark - private event
- (void)getMsgListWithPage:(NSInteger)cPage isDownLoad:(BOOL)downLoad
{
    @weakify(self);
   [self.msgPresenter getMsgListWithTimeStamp:self.timeStamp Page:cPage Limit:10 Success:^(NSArray *dataArr, NSTimeInterval timeStamp, NSInteger totalPage, NSInteger currentPage) {
       @strongify(self);
       if (downLoad) {
           if (self.tableView.mj_footer.state == MJRefreshStateNoMoreData) {
               self.tableView.mj_footer.state = MJRefreshStateIdle;
           }
           if (totalPage == 0) {
               [self.tableView setNoDataFooterText];
               [self.tableView.mj_footer endRefreshingWithNoMoreData];
           }
           if (self.dataArr.count > 0) {
               [self.dataArr removeAllObjects];
           }
           [self.dataArr addObjectsFromArray:dataArr];
           self.currentPage = currentPage + 1;
           [self.tableView.mj_header endRefreshing];
           
       }else{
           if (currentPage == self.currentPage) {
               if (self.currentPage < totalPage) {
                   [self.tableView.mj_footer endRefreshing];
               }else{
                   [self.tableView setNoMoreDataFooterText];
                   [self.tableView.mj_footer endRefreshingWithNoMoreData];
               }
               self.currentPage ++;
               [self.dataArr addObjectsFromArray:dataArr];
           }
       }
       
       [self.tableView reloadData];

   } Failure:^(NSString *fail) {
       @strongify(self);
       [self.tableView.mj_header endRefreshing];
       [self.tableView.mj_footer endRefreshing];
   }];
}

- (void)downLoadNewData
{
    [self getMsgListWithPage:1 isDownLoad:YES];
}

- (void)upLoadMoreData
{
    [self getMsgListWithPage:self.currentPage isDownLoad:NO];
}


/**
 这里请求你信息详情.只是为了告知后台,此条消息已经读取.

 @param msgId <#msgId description#>
 */
- (void)changeMsgIsReaded:(NSString *)msgId
{
     __block NSInteger cc = [[UIApplication sharedApplication] applicationIconBadgeNumber];
    [self.msgPresenter getMsgDetailWithMsgId:msgId Success:^(id data) {
        cc -- ;
//        [[UIApplication sharedApplication] setApplicationIconBadgeNumber:cc];
        [LZNotificationPresenter setNewBadgeCount:cc];
        
    } Failure:^(NSString *fail) {
        
    }];
}

#pragma mark - configure Refresh UI
/**
 添加下拉刷新
 */
- (void)addHeaderRefresh {
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downLoadNewData)];
    [self.tableView configHeaderRefreshText];
}

/**
 添加上拉刷新
 */
- (void)addFooterRefresh {
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upLoadMoreData)];
    [self.tableView configFooterRefreshText];
}


#pragma mark -
#pragma mark UI
- (void)configureUI
{
    self.umLogPageViewName = @"消息中心";
    self.title = LZLocalizedString(@"message_message_center", nil);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"LZMyMessageCenterCell" bundle:nil] forCellReuseIdentifier:@"cell"];
}

#pragma mark -
#pragma mark tableview delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LZMessageModel *m = self.dataArr[indexPath.row];
    NSString *str = @"";
    switch (m.msgType) {
        case kMsgCenterType_resAuthRegected: {//餐厅认证被拒
            str = LZLocalizedString(@"message_restaurant_auth_regected", nil);
        }
            break;
        case kMsgCenterType_resAuthSuccess:{//餐厅认证通过
            str = LZLocalizedString(@"message_restaurant_auth_success", nil);
        }
            break;
        case kMsgCenterType_photosDelete:{//删除违规照片
            str = LZLocalizedString(@"message_photos_delete", nil);
        }
            break;
        case kMsgCenterType_finicalRecode:{//结账通知
            str = LZLocalizedString(@"message_new_finical", nil);
        }
            break;
        case kMSgCenterType_resComment:{//餐厅评论
            str = LZLocalizedString(@"message_new_review", nil);
        }
            break;
        case kMsgCenterType_videoComment:{//视频评论
            str = LZLocalizedString(@"message_new_review", nil);
        }
            break;
        default:
            break;
    }

    return [LZMyMessageCenterCell getCellHeightWithText:str];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LZMyMessageCenterCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    LZMessageModel *m = self.dataArr[indexPath.row];
    [cell loadContentWithModel:m];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    LZMessageModel *modelTemp = self.dataArr[indexPath.row];
    [self changeMsgIsReaded:modelTemp.msgId];
    modelTemp.isRead = YES;
    
    switch (modelTemp.msgType) {
        case kMsgCenterType_resAuthRegected: {//餐厅认证被拒
            if ([GVUserDefaults standardUserDefaults].authType != kAuthType_completeAuth) {
                LZRestaurantAuthenticationViewController *vc = [[LZRestaurantAuthenticationViewController alloc] initWithNibName:@"LZRestaurantAuthenticationViewController" bundle:nil];
                vc.regected = YES;
                [self.navigationController pushViewController:vc animated:YES];
            }
            
        }
            break;
            
        case kMsgCenterType_resAuthSuccess:{//餐厅认证通过
            
            if ([GVUserDefaults standardUserDefaults].authType != kAuthType_completeAuth) {
                [GVUserDefaults standardUserDefaults].authType = kAuthType_completeAuth;
                LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"message_res_auth_success_exit", nil) andImage:nil cancelButtonTitle:nil otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
                
                [alert show];
                
                alert.clickButtonIndexBlock = ^(NSInteger index) {
                    exit(0);
                };
            }

        }
            break;
            
        case kMsgCenterType_photosDelete:{//删除违规照片
            LZManagePictureContentViewController *vc = [[LZManagePictureContentViewController alloc]initWithNibName:@"LZManagePictureContentViewController" bundle:nil];
            vc.isCurrentVCNotChildVC = YES;
            vc.delBatch = modelTemp.bussinessId;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;  
            
        case kMsgCenterType_finicalRecode:{//结账通知
            
            LZFinancialDetailViewController *vc = [[LZFinancialDetailViewController alloc] initWithNibName:@"LZFinancialDetailViewController" bundle:nil];
            vc.payID = modelTemp.bussinessId;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
        case kMSgCenterType_resComment:{//餐厅评论
            LZMsgCenterCommentViewController *vc = [[LZMsgCenterCommentViewController alloc] initWithNibName:@"LZMsgCenterCommentViewController" bundle:nil];
            vc.reviewType = ReviewType_Restaurants;
            vc.commentId = modelTemp.bussinessId;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
        case kMsgCenterType_videoComment:{//视频评论
            LZMsgCenterCommentViewController *vc = [[LZMsgCenterCommentViewController alloc] initWithNibName:@"LZMsgCenterCommentViewController" bundle:nil];
            vc.reviewType = ReviewType_Video;
            vc.commentId = modelTemp.bussinessId;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
        default:
            break;
    }
    
    [self.tableView reloadData];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath //last ios 8
{
    @weakify(self);
    UITableViewRowAction *rowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"      " handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        @strongify(self);
        [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
        LZMessageModel *modelTemp = self.dataArr[indexPath.row];
        [self.msgPresenter deleteMsgWithID:modelTemp.msgId Success:^(id data) {
            [self stopLoadingViewForView:self.view];
            [self.dataArr removeObjectAtIndex:indexPath.row];
            //发现删除动画不可调控. 这两句代码是防止删除动画时,删除按钮往上窜的效果.
            LZMyMessageCenterCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            cell.deleteImgView.hidden = YES;
            [self.tableView beginUpdates];
            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            [self.tableView endUpdates];
            
            //删除成功后重新拉取数据
            [self.tableView.mj_header beginRefreshing];

        } Failure:^(NSString *fail) {
            [self stopLoadingViewForView:self.view];
        }];
        
    }];
    
    rowAction.backgroundColor = [UIColor clearColor];
    
    return @[rowAction];
}



@end
